'''
Created on 9 nov. 2012

@author: jurgen_reintjes
'''
import socket
from threading import Thread

class Client(Thread):
    def __init__(self, vision, host, port):
        Thread.__init__(self)
        self.client_socket = socket.socket(socket.AF_INET, socket.SOCK_STREAM)
        self.running = False
        self.socket_available = False
        self.port = port
        self.host = host
        self.vision = vision
        pass
    
    def connect(self):
        try:
            self.client_socket.connect((self.host, self.port))
            self.running = True
            self.socket_available = True
            
            Thread.start(self)
        except socket.error, (value,message): 
            print("error creating connection "+ message)
            self.socket_available = False
            self.running = False
    
    def run(self):
        try:
            while self.running:
                result = self.client_socket.recv(1024)
                result = result.split(" ")
                if result[0] == 'screen':
                    self.vision.setResolution(int(result[2]), int(result[1]))
                elif result[0] == "calibrate":
                    while self.vision.calibrate() == False:
                        pass
                    self.send("Calibrated\n")
        except socket.error, (value,message): 
            print("lost connection")
            self.running = False
            self.socket_available = False
            
        self.disconnect()
        self.client_socket = None                
    
    def send(self,data):
        if self.socket_available:
            try:
                self.client_socket.send(data)
            except socket.error, (value,message): 
                print("lost connection")
                self.running = False
            
    def disconnect(self):
        self.running = False
        if self.socket_available:
            self.client_socket.send("Quit\n")
            self.client_socket.shutdown(socket.SHUT_RDWR)
            self.client_socket.close()
            self.socket_available = False
    
        
    
